package routers

import (
	"github.com/gin-contrib/pprof"
	"github.com/gin-gonic/gin"
	ginSwagger "github.com/swaggo/gin-swagger"
	"github.com/swaggo/gin-swagger/swaggerFiles"
	"io"
	"os"
	_ "shop-api/docs"
	"shop-api/middleware"
	"shop-common/library/variables"
)

func InitWebRouter(accessInfoLogger, accessErrLogger io.Writer) *gin.Engine {
	var router *gin.Engine
	// 非调试模式（生产模式） 日志写到日志文件
	if !variables.AppDebug {
		//1.将日志写入日志文件
		gin.DefaultWriter = io.MultiWriter(os.Stdout, accessInfoLogger)
		gin.DefaultErrorWriter = io.MultiWriter(os.Stderr, accessErrLogger)
		// 2.如果是有nginx前置做代理，基本不需要gin框架记录访问日志，开启下面一行代码，屏蔽上面的三行代码，性能提升 5%
		//gin.SetMode(gin.ReleaseMode)
		router = gin.Default()
	} else {
		// 调试模式，开启 pprof 包，便于开发阶段分析程序性能
		router = gin.Default()
		pprof.Register(router)
	}

	return apiRouter(router)
}

func apiRouter(router *gin.Engine) *gin.Engine {
	router.GET("/swagger/*any", ginSwagger.WrapHandler(swaggerFiles.Handler))
	router.Use(middleware.Cors())
	router.Use(middleware.Logger())
	public := router.Group("")
	{
		publicIndexImgs(public)
		publicProd(public)
		publicCategory(public)
		publicNotice(public)
		publicTag(public)
	}

	private := router.Group("")
	{
		privateArea(private)
		privateAddr(private)
		privateShopCart(private)
	}
	return router
}
